//
//  RegisterViewController.m
//  51-Tour
//
//  Created by xiang ying on 14-3-20.
//  Copyright (c) 2014年 xiang ying. All rights reserved.
//

#import "RegisterViewController.h"
#import "SVProgressHUD.h"
#import "ServiceManage.h"

@interface RegisterViewController ()<UITextFieldDelegate>{
    
    UITextField *textField1 ;
    UITextField *textField2 ;
    UITextField *textField3 ;
    
    NSInteger   _seconds;
}

@property(nonatomic,strong)UIButton *valiateCodeBtn;

@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)popself{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [super popself];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initNavigationItme:[[DataCenter instance] getStringForKey:@"MobileVerifate"]];

    
    UIView *bg = [[UIView alloc] initWithFrame:CGRectMake((320-260)/2, 40, 260, 40)];
    bg.backgroundColor = [UIColor whiteColor];
    bg.layer.shadowOffset = CGSizeMake(bg.frame.size.width, bg.frame.size.height-1);
    bg.layer.shadowColor = [UIColor darkGrayColor].CGColor;
    
    textField1 = [[UITextField alloc] initWithFrame:CGRectMake(5, (bg.frame.size.height-30)/2, bg.frame.size.width-100, 30)];
    textField1.delegate = self;
    textField1.placeholder = [[DataCenter instance] getStringForKey:@"EnterPhone"];// @"请输入您的手机号";
    textField1.keyboardType = UIKeyboardTypePhonePad;
    textField1.tag = 1;
    [textField1 addTarget:self action:@selector(textBegin:) forControlEvents:UIControlEventEditingDidBegin];
    [bg addSubview:textField1];
    
    _valiateCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _valiateCodeBtn.frame = CGRectMake(bg.frame.size.width-100, 7, 80, 30);
    _valiateCodeBtn.layer.borderWidth = 1;
    _valiateCodeBtn.layer.cornerRadius = 4;
    [_valiateCodeBtn setTitleColor:THEMECOLOR forState:UIControlStateNormal];
    _valiateCodeBtn.layer.borderColor = THEMECOLOR.CGColor;
    _valiateCodeBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_valiateCodeBtn setTitle:[[DataCenter instance] getStringForKey:@"GetCode"] forState:UIControlStateNormal];
    [_valiateCodeBtn addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    [bg addSubview:_valiateCodeBtn];
    
    [self.contentView addSubview:bg];
    
    
    bg = [[UIView alloc] initWithFrame:CGRectMake((320-260)/2, 40+40+10, 260, 40)];
    bg.backgroundColor = [UIColor whiteColor];
    bg.layer.shadowOffset = CGSizeMake(bg.frame.size.width, bg.frame.size.height-1);
    bg.layer.shadowColor = [UIColor darkGrayColor].CGColor;
    
    textField2 = [[UITextField alloc] initWithFrame:CGRectMake(5, (bg.frame.size.height-30)/2, bg.frame.size.width-10, 30)];
    textField2.delegate = self;
    textField2.placeholder = [[DataCenter instance] getStringForKey:@"ValicateCode"];//@"验证码";
    textField2.tag = 2;
    textField2.keyboardType = UIKeyboardTypePhonePad;
    [textField2 addTarget:self action:@selector(textBegin:) forControlEvents:UIControlEventEditingDidBegin];
    [bg addSubview:textField2];
    
    [self.contentView addSubview:bg];
    
    bg = [[UIView alloc] initWithFrame:CGRectMake((320-260)/2, 40+(40+10)*2, 260, 40)];
    bg.backgroundColor = [UIColor whiteColor];
    bg.layer.shadowOffset = CGSizeMake(bg.frame.size.width, bg.frame.size.height-1);
    bg.layer.shadowColor = [UIColor darkGrayColor].CGColor;
    
    textField3 = [[UITextField alloc] initWithFrame:CGRectMake(5, (bg.frame.size.height-30)/2, bg.frame.size.width-10, 30)];
    textField3.delegate = self;
    textField3.tag = 3;
    textField3.placeholder = [[DataCenter instance] getStringForKey:@"RecommendPhone"];//@"推荐人手机号（可填可不填）";
    textField3.keyboardType = UIKeyboardTypePhonePad;
    [textField3 addTarget:self action:@selector(textBegin:) forControlEvents:UIControlEventEditingDidBegin];
    [bg addSubview:textField3];
    
    [self.contentView addSubview:bg];
    
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    [sure setFrame:CGRectMake(bg.frame.origin.x, bg.frame.origin.y+bg.frame.size.height+20, bg.frame.size.width, 44)];
    [sure setBackgroundColor:THEMECOLOR];
    [sure setTitle:[[DataCenter instance] getStringForKey:@"Submit"] forState:UIControlStateNormal];
    [sure addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:sure];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEdit)];
    [self.contentView addGestureRecognizer:tap];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    if (textField == textField1||textField == textField3) {
//        if (range.location>10) {
//            //11位手机号码
//            return NO;
//        }
//    }else if(textField == textField2){
//        if (range.location>5) {
//            //6位验证码
//            return NO;
//        }
//    }

    return YES;
}
#pragma mark - 
-(BOOL)checkInput{
    if (textField1.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"EnterPhone"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
        [alert show];
        return NO;
    }
    if ([[textField1 text] length]!=11) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"login_mobile_toast"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
        [alert show];
        return NO;
    }
    if ([[textField2 text] length]==0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"login_verifyCode_toast"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
        [alert show];
        return NO;
    }
    if ([[textField3 text] length]!=0&&[[textField3 text] length]!=11) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"login_mobile_toast"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
        [alert show];
        return NO;
    }
    if ([textField1.text isEqualToString:textField3.text]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"login_recommend_toast2"] delegate:nil cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Sure"] otherButtonTitles: nil];
        [alert show];
        return NO;
    }
    return YES;
}

-(void)textBegin:(UITextField*)textField{
    [self.contentView setContentSize:CGSizeMake(320, self.contentView.frame.size.height+60)];
    switch (textField.tag) {
        case 1:
            //手机号
            break;
        case 2:
            //验证码
            break;
        case 3:
            //推荐手机号
            
            break;
        default:
            break;
    }
}

-(void)endEdit{
    [self.view endEditing:YES];
    [self.contentView setContentSize:self.contentView.frame.size];
}

-(void)updateSecondes{
    if (_seconds < 0) {
        //停止
        [_valiateCodeBtn setTitle:[[DataCenter instance] getStringForKey:@"GetCode"] forState:UIControlStateNormal];
        _valiateCodeBtn.userInteractionEnabled = YES;
    }else{
        [_valiateCodeBtn setTitle:[NSString stringWithFormat:@"%d s",_seconds] forState:UIControlStateNormal];
        [self performSelector:@selector(updateSecondes) withObject:nil afterDelay:1];
    }
    _seconds--;
}


-(void)getCode:(id)sender{
    if (textField1.text.length !=11) {
        [SVProgressHUD showErrorWithStatus:[[DataCenter instance] getStringForKey:@"login_mobile_toast"]];
        return;
    }
    //获取验证码
    [NSObject cancelPreviousPerformRequestsWithTarget:self];

    [SVProgressHUD showWithStatus:[[DataCenter instance] getStringForKey:@"loading"]];

    [ServiceManage getRegisterCodeRequestInfo:@{@"Mobile": textField1.text} completion:^(RespondDTO *respond) {
        if (respond.flag == respond_success) {
            _seconds = 90;
            NSLog(@"%@",respond.data);
            [self updateSecondes];
            [SVProgressHUD showSuccessWithStatus:TIP_SUCCESS];
            _valiateCodeBtn.userInteractionEnabled = NO;
        }else{
            [_valiateCodeBtn setTitle:[[DataCenter instance] getStringForKey:@"GetCode"] forState:UIControlStateNormal];
            _valiateCodeBtn.userInteractionEnabled = YES;
            [SVProgressHUD showErrorWithStatus:TIP_ERROR];
        }
    }];
}

-(void)login:(id)sender{
    if ([self checkInput]) {
        //提交
        [ServiceManage setRegisterRequestInfo:@{@"Mobile": textField1.text,@"ValidateCode":textField2.text,@"RecommendPeople":textField3.text} completion:^(RespondDTO *respond) {
            if (respond.flag == respond_success) {
                [self popself];
                [SVProgressHUD showSuccessWithStatus:[[DataCenter instance] getStringForKey:@"loginsuccess"]];
            }else{
                [SVProgressHUD showErrorWithStatus:[[DataCenter instance] getStringForKey:@"loginfailed"]];
            }
        }];
    }
}

@end
